import { GetOpenaiChatByText, GetImageFormat, GetTextFormat } from './openai';
import { bufferToBase64 } from './crypto';

// 从 cloudflare worker KV 命名空间绑定 获取
const GetTenantAccessToken = async (env: Env) => {
	let tenant_access_token = await env.NAMESPACE.get('feishu_tenant_access_token', { type: 'text' });
	if (tenant_access_token) {
		return tenant_access_token;
	}
	const response = await fetch(env.FeiShuUrl + '/open-apis/auth/v3/tenant_access_token/internal', {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ app_id: env.FeiShuAppId, app_secret: env.FeiShuAppSecret }),
	});
	const respJson = (await response.json()) as { tenant_access_token: string };
	tenant_access_token = respJson['tenant_access_token'];
	env.NAMESPACE.put('feishu_tenant_access_token', tenant_access_token, { type: 'text', expirationTtl: 3600 });

	return tenant_access_token;
};

// 回复类型 飞书消息格式
const formatFeiShuSendMsg = (openaiRespContent: string, reply_in_thread: boolean) => {
	const title = reply_in_thread ? '' : '上下文的回复';
	const content = {
		elements: [{ tag: 'markdown', content: openaiRespContent }],
		header: { template: 'blue', title: { content: title, tag: 'plain_text' } },
	};
	return {
		content: JSON.stringify(content),
		msg_type: 'interactive',
		reply_in_thread: reply_in_thread, // 是否使用飞书话题模式回复
	};
};

// 获取飞书图片 base64
const GetImageBase64 = async (env: Env, image_key: string, message_id: string) => {
	const tenantAccessToken = await GetTenantAccessToken(env);
	const url = `${env.FeiShuUrl}/open-apis/im/v1/messages/${message_id}/resources/${image_key}?type=image`;
	const headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + tenantAccessToken };
	const response = await fetch(url, { method: 'GET', headers: headers });

	const imageBuffer = await response.arrayBuffer();
	const base64Image = bufferToBase64(imageBuffer);

	const base64ImageUrl = 'data:image/jpg;base64,' + base64Image;
	return base64ImageUrl;
};

// 获取指定消息的内容
const GetFeiShuMessageContent = async (env: Env, message_id: string): Promise<any> => {
	const tenantAccessToken = await GetTenantAccessToken(env);
	const url = `${env.FeiShuUrl}/open-apis/im/v1/messages/${message_id}`;
	const headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + tenantAccessToken };
	const response = await fetch(url, { method: 'GET', headers: headers });

	return await response.json();
};

// 	群回话类型，@机器人才会触发回复
const IsReply = (FeiShuMessage: any) => {
	let is_reply = true;
	if (FeiShuMessage.chat_type == 'group') {
		is_reply = false;
		for (const line of FeiShuMessage.mentions) {
			console.log('line: ', line.name);
			if (line.name == 'chatgpt') {
				is_reply = true;
			}
		}
	}
	return is_reply;
};

// 获取上文 引用信息
const GetParentMsg = async (env: Env, parent_id: string) => {
	const parentContent = await GetFeiShuMessageContent(env, parent_id);
	// console.log('parentContent: ', parentContent.data.items);
	let userPrompt = [];
	const role = parentContent.data.items[0].sender.id == env.FeiShuAppId ? 'assistant' : 'user';
	for (const line of parentContent.data.items) {
		console.log('line: ', line.sender.id);
		if (line.msg_type == 'image') {
			const image_key = JSON.parse(line.body.content).image_key;
			const base64ImageUrl = await GetImageBase64(env, image_key, line.message_id);
			userPrompt.push(await GetImageFormat(base64ImageUrl));
		}
		for (const element of JSON.parse(line.body.content).elements) {
			// 拼接
			let c = '';
			for (const pj of element) {
				c += pj.text || '';
			}
			userPrompt.push(GetTextFormat(c));
		}
	}
	return { role: role, content: userPrompt };
};

// 发送飞书消息通知
const SendFeiShuMsg = async (env: Env, decryptJsonFeiShuData: any) => {
	let userPromptList = [];

	let FeiShuMessage = decryptJsonFeiShuData.event.message;

	if (!IsReply(FeiShuMessage)) {
		return;
	}

	const userContent = JSON.parse(FeiShuMessage.content);
	if (!FeiShuMessage.thread_id && FeiShuMessage.parent_id) {
		console.log('引用上文 parent_id: ', FeiShuMessage.parent_id);
		userPromptList.push(await GetParentMsg(env, FeiShuMessage.parent_id));
	} else if (FeiShuMessage.thread_id) {
		console.log('话题 thread_id: ', FeiShuMessage.thread_id);
	}

	// console.log('feishu event userContent: ', userContent);
	if (FeiShuMessage.message_type == 'post') {
		let userPrompt = [];
		for (const line of userContent.content) {
			if (line[0].tag == 'img') {
				const base64ImageUrl = await GetImageBase64(env, line[0].image_key, FeiShuMessage.message_id);
				userPrompt.push(await GetImageFormat(base64ImageUrl));
			} else if (line[0].tag == 'text') {
				userPrompt.push(GetTextFormat(line[0].text));
			}
		}
		userPromptList.push({ role: 'user', content: userPrompt });
	} else if (FeiShuMessage.message_type == 'image') {
		const base64ImageUrl = await GetImageBase64(env, userContent.image_key, FeiShuMessage.message_id);
		userPromptList.push({ role: 'user', content: [await GetImageFormat(base64ImageUrl)] });
	} else {
		userPromptList.push({ role: 'user', content: [GetTextFormat(userContent.text)] });
	}

	// 请求 OPENAI API，获取返回内容
	const respJson = await GetOpenaiChatByText(env, userPromptList);
	const openaiRespContent = respJson.choices[0].message.content;

	// 发送飞书信息
	const tenantAccessToken = await GetTenantAccessToken(env);
	// const url = env.FeiShuUrl + '/open-apis/im/v1/messages?receive_id_type=chat_id';
	const url = `${env.FeiShuUrl}/open-apis/im/v1/messages/${decryptJsonFeiShuData.event.message.message_id}/reply?receive_id_type=chat_id`;
	const reply_in_thread = FeiShuMessage.chat_type == 'group' ? false : true;
	let body = formatFeiShuSendMsg(openaiRespContent, reply_in_thread);
	const headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + tenantAccessToken };
	await fetch(url, { method: 'POST', headers: headers, body: JSON.stringify(body) });
};

export { SendFeiShuMsg };
